﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Web.Mvc;

using CloudSoft.Workflows;

using ERPStore.Extensions;

namespace ERPStore.Indexers.Lucene.Workflows.Activities
{
	public sealed class ScheduledBuilder : CodeActivity
	{
		public InArgument<string> IndexPath { get; set; }

		protected override void Execute(CodeActivityContext context)
		{
			string indexPath = context.GetValue(this.IndexPath);
			var logger = GlobalConfiguration.Configuration.DependencyResolver.GetService<ERPStore.Logging.ILogger>();
			var builder = GlobalConfiguration.Configuration.DependencyResolver.GetService<Services.IndexBuilder>();

			string fileName = System.IO.Path.Combine(indexPath, @"catalogindexation.txt");
			var fileInfo = new System.IO.FileInfo(fileName);
			var topTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 2, 50, 0);
			if (fileInfo.Exists
				&& fileInfo.LastWriteTime.AddDays(1) > topTime)
			{
				logger.Info("BuildFullTextIndexWorkflow : Index existant");
				builder.EnableLuceneCatalogService();
			}
			else
			{
				logger.Warn("BuildFullTextIndexWorkflow : Début de la construction : {0}", indexPath);

				try
				{
					builder.Start();
				}
				catch(Exception ex)
				{
					logger.Error(ex);
				}
			}
		}
	}
}
